<?php
/**
 * Created by PhpStorm.
 * User: kb130
 * Date: 2018/7/3
 * Time: 16:57
 */

namespace App\Observers;


use App\Exceptions\NoPermissionException;
use App\Models\ReviewTemplate;

class ReviewTemplateObserver
{
    protected const ADMIN = 'Admin';

    protected const USER  = 'User';

    public function creating(ReviewTemplate $reviewTemplate)
    {
        $reviewTemplate->user_id = request()->user()->id;
    }

    public function updating(ReviewTemplate $reviewTemplate)
    {
        $userModel = request()->user();
        $shortName = class_short_name($userModel);

        throw_if(
            static::USER === $shortName && $reviewTemplate->user_id !== $userModel->id,
            new NoPermissionException()
        );

        if (static::ADMIN === $shortName) {
            $reviewTemplate->verifier_id = $userModel->id;
        }
    }
}